Ext.ns('Wlanauth.user');

Wlanauth.user.BatchAddPanel = Ext.extend(Ext.Panel,{
	title:'用户资料批量新增',
	baseCls:'x-plant',
	logWindow:null,
	iconCls:'toExcel',
	constructor:function(config){
		Ext.apply(this,config);
		var allowDownload = ZZExt.ApplicationContext.actionAccessable('wlanauth.user.download');
		function filenameRender(val,meta,record,row,col,store){
			if(allowDownload){
				return '<a href="downloadUserFile.action?entity.id='+record.get('id')+'" title="点击下载" target="_blank">'+val+'</a>'
			} else {
				return val;
			}
		}
		//文件上传域
		var fileuploadField= new Ext.ux.form.FileUploadField({
			fieldLabel:'文件',
			emptyText: '请选择文件',
			buttonText: '浏览',
			name:'upload',
			width:300
		});
	 	var _html='<ul style="font-size:12px;padding:5px;color:#666999"><li>同步方式:上传文件并处理,立即返回结果</li><li>异步方式:上传文件后台处理,不立即返回结果</li></ul>';
	 	
		this.uploadFileFormPanel = new Wlanauth.BaseFormPanel({
			region : 'north',
			height:140,
			margins : '5',
			padding:5,
			fileUpload: true,
			tbar:[{
				text:'异步上传',
				iconCls:'uploadfile',
				handler:this.uploadFileUnsync,
				scope:this
			},'-',{
				text:'同步上传',
				iconCls:'uploadfile',
				handler:this.uploadFileSync,
				scope:this
			},'-',{
				text:'格式说明',
				handler:this.showDoc
			}],
			layout:'form',
			items:[{
				xtype:'compositefield',
				fieldLabel:'文件类型',
				items:[{
					xtype:'radio',name:'fileType',boxLabel:'智能匹配&nbsp;',checked:true,value:'auto'
				},{
					xtype:'radio',name:'fileType',boxLabel:'Excel文档&nbsp',value:'excel'
				},{
					xtype:'radio',name:'fileType',boxLabel:'文本文件&nbsp',value:'txt'
				}]
			},fileuploadField,{
				border:false,
				html:_html
			}]
		});
		//历史记录
		this.historyGridStore = new Ext.data.JsonStore({
			url:'userFile!list.action',
			totalProperty:'data',
			root:'rows',
			autoLoad:true,
			baseParams:{limit:20},
			fields:['id','name','type','length','path','totalNum','successNum','batchId',
			        {name:'uploadTime',type:'date',dateFormat:'Y-m-d H:i:s'}]
			
		});
		this.historyGrid = new Wlanauth.BaseGridPanel({
			region : 'center',
			margins : 5,
			border:false,
			loadMask:true,
			store:this.historyGridStore,
			cm:new Ext.grid.ColumnModel({
				columns:[
				    new Ext.grid.RowNumberer(),
				    {header:'批次号',dataIndex:'batchId',width:120},
				    {header:'文件名',id:'name',dataIndex:'name',width:120,renderer:filenameRender},
					{header:'文件类型',dataIndex:'type',width:120},
				    {header:'文件大小(KB)',dataIndex:'length',width:120,sortable:true,renderer:function(val){return val/1024;}},
				    {header:'记录总数',dataIndex:'totalNum',renderer:this.usedOctRender,sortable:true},
				    {header:'成功入库数',dataIndex:'successNum',width:100,sortable:true},
				    {header:'上传时间',dataIndex:'uploadTime',width:150,renderer:Ext.util.Format.dateRenderer("Y-m-d H:i:s"),sortable:true}
			    ]}),
		     viewConfig: {
	            forceFit: true
			 },
			 autoExpandColumn:'name',
			 tbar:[{
				 text:'删除',
				 iconCls:'delete',
				 handler:this.deleteObject,
				 hidden:!ZZExt.ApplicationContext.actionAccessable('wlanauth.user.batchadd.delete'),
				 scope:this
			 },'-','双击行查看批次错误日志']
		});
		
	 	Wlanauth.user.BatchAddPanel.superclass.constructor.call(this,{
			waitMsgTarget: true,
	        padding:5,
	        layout:'border',
	        items:[this.uploadFileFormPanel,this.historyGrid]
     	});
	 	this.historyGrid.on('rowdblclick',this.viewDetail,this);
	 	this.historyGrid.addSimpleSearchBar([['批次号','entity.batchId'],['文件名','entity.name']]);
	},
	uploadFileUnsync:function(){
		this.uploadFile(false);//一步
	},
	uploadFileSync:function(){
		this.uploadFile(true);//同步
	},
	uploadFile:function(sync){
		var form = this.uploadFileFormPanel.getForm();
		var filename = form.findField('upload').getValue();
		if(filename=='') {
    		Ext.Msg.alert('提示','文件不能为空');
    		return false;
    	}
    	var ext = filename.substring(filename.lastIndexOf('.'));
    	if('|.xls|.txt'.indexOf("|"+ext.toLowerCase())<0){
    		Ext.Msg.alert('提示','请选择合法的文件');
    		return false;
    	}
    	var grid = this.historyGrid;
    	form.submit({
    		waitMsg:'正在上传...',
			url:'uploadUserFile.action',
			params:{processSyncFlag:sync},
			scope:this,
			success:function(form,action){
				if(action.result.success){ //文件上传成功
					//如果是同步处理方式，刷新列表，弹出提示
					if(sync){ 
						grid.getStore().reload();
						var data = action.result.data;
						if(data.success){
							var proccesResult = data.processResult;
							if(proccesResult.length==1){
								var r = proccesResult[0];
								if(r.successNum==r.totalNum){ //如果成功数与总数相同，只提示
									Ext.Msg.alert('提示','批量导入用户成功!');
								} else {
									var win = this.getLogWindow();
									win.show();
									win.reset(r);
								}
							}
							
						} else {
							Ext.Msg.alert('提示',data.processResult);
						}
					} else {
						Ext.Msg.alert('提示','文件已上传');
					}
					
				} else {
					Ext.Msg.alert('提示','文件上传失败');
				}
			}
		});
    	
	},
	
	getLogWindow:function(){
		if(this.logWindow == null){
			this.logWindow = new Wlanauth.user.BatchUploadLogWindow();
		}
		return this.logWindow;
	},
	viewDetail:function(){
		var r = this.historyGrid.getSelectionModel().getSelected();
		this.getLogWindow().show();
		this.getLogWindow().reset({batchId:r.get('batchId'),id:r.get('id')});
	},
	deleteObject:function(){
		var grid = this.historyGrid;
		var r = grid.getSelectionModel().getSelected();
		if(!r){Ext.Msg.alert('提示','请选择一项');return;}
		Ext.Msg.confirm('警告','您确定删除该条记录吗?',function(btn){
			if(btn=='yes'){
				Ext.Msg.wait('删除...');
				Ext.Ajax.request({
					url:'userFile!delete.action?entity.id='+r.get('id'),
					success:function(response,opts){
						if(checkException(response)){
							Ext.Msg.alert('提示','删除成功');
							grid.getStore().reload();
						}
					}
				
				});
			} 
		});
		
	},
	showDoc:function(){
		if(this.docWin == null){
			this.docWin = new Ext.Window({
				closeAction:'hide',
				title:'格式说明',
				width:550,
				resizable:false,
				items:[{
					xtype:'framepanel',
					height:270,
					border:false,
					src:'js/user/BatchAddDoc.html'
				}]
			});
			
		}
		this.docWin.show();
	}
});

Wlanauth.user.BatchUploadLogWindow = Ext.extend(Ext.Window,{
	title:'批量出错日志>>批次号:<font style="color:#eb3d5d">loading...</font>',
	width:700,
	height:450,
	closeAction:'hide',
	constructor:function(config){
		Ext.apply(this,config);
		//历史记录
		this.store = new Ext.data.JsonStore({
			url:'uploadFileLog!list.action?&entity.type=ERROR',
			totalProperty:'data',
			root:'rows',
			autoLoad:false,
			baseParams:{limit:15},
			fields:['id','msg','type','orginalValue','lineNum','description',
			        {name:'createTime',type:'date',dateFormat:'Y-m-d H:i:s'}]
			
		});
		this.grid = new Wlanauth.BaseGridPanel({
			region : 'center',
			margins : 5,
			border:false,
			store:this.store,
			cm:new Ext.grid.ColumnModel({
				columns:[
				    {header:'行号',dataIndex:'lineNum',width:70,sortable:true},
				    {header:'原因',dataIndex:'msg',width:200},
				    {header:'备注',id:'desc',dataIndex:'description',sortable:false},
				    {header:'产生时间',dataIndex:'createTime',width:120,renderer:Ext.util.Format.dateRenderer("Y-m-d H:i:s"),sortable:true}
			    ]}),
			 autoExpandColumn:'desc'
		});
		Wlanauth.user.BatchUploadLogWindow.superclass.constructor.call(this,{
			border:false,
			layout:'fit',
			items:[this.grid]
		});
	},
	reset:function(r){
		this.setTitle('批量出错日志>>批次号:<font style="color:#eb3d5d">'+r.batchId+'</font>');
		
		Ext.apply(this.grid.store,{baseParams:{'entity.uploadFileId':r.id}});
		this.grid.getStore().reload({params:{start:0}});
		
	}
});

Ext.reg('wlanauth.user.batchaddpanel',Wlanauth.user.BatchAddPanel);